<?php

namespace humhub\modules\api\controllers;

use Yii;
use yii\web\HttpException;
use humhub\modules\api\models\Task;
use humhub\modules\api\models\TaskUser;
use humhub\modules\post\models\Post;
use humhub\modules\api\models\User;
#use humhub\modules\api\models\Space;
use humhub\modules\space\models\Space;

use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;

/**
 * 课程（Course）相关接口
 */
class CourseController extends Base2Controller
{

    /**
     * @inheritdoc
     */
    public $hideSidebar = true;

    /**
     * @inheritdoc
     */
    public function init(){
        $cClass = \Yii::$app->request->post('containerClass');
        if( $cClass == 'space' ){
            $_GET['sguid'] = \Yii::$app->request->post('containerGuid');
            $_POST['containerClass'] = 'humhub\modules\space\models\Space';
        }
        //stream
        if( isset($_GET['s']) ){
            $_GET['sguid'] = Yii::$app->request->get('s');
        }

        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                //QueryParamAuth::className(),
                HttpBearerAuth::className(),
            ],
        ];
        return $behaviors;
    }

    /**
     * 【OFF】获取指定课程的子课程列表(space.post)
     *
     * GET api/course/stream?s=[:guid]&limit=[4]&filters=&sort=c&from=[66]&mode=normal
     *
     * get.s : 课程Space的guid
     *
     * get.limit : 单次获取总量
     *
     * get.from : 起始wallEntryID，默认为空''=第一页
     *
     * @return array 结构和任务是一样的
     */
    public function actionStream(){
        throw new \yii\web\BadRequestHttpException('课程未找到.');
        if($this->contentContainer->s_type != 2){
            throw new \yii\web\BadRequestHttpException('课程未找到.');
        }
        $stream = Yii::createObject([
            'class' => \humhub\modules\api\cccstream\ContentContainerStream::className(),
            'contentContainer' => $this->contentContainer
        ], ['stream', $this]);
        return $stream->run();
    }


    /**
     * 获取主课程详情
     *
     * GET /api/course?s=[sguid]
     *
     * get.s : 课程Space的guid
     *
     * @return 结构和任务是一样的，区别之处有：1.返回一个讲师信息; 2.没有部分用户列表; 3.目录单独获取 4.ismember购买课程状态
     */
    public function actionInfo(){
        $space = $this->contentContainer;
        if( $space->s_type != 2 ){
            throw new \yii\web\BadRequestHttpException('课程未找到.');
        }
        $id = $space->id;

        $s = [];
        $s['name'] = $space->name;
        $s['guid'] = $space->guid;
        //Task
        $s['tags']   = \humhub\widgets\RichText::widget(['text' => $space->tags, 'record' => $space]);
        $s['s_type'] = $space->s_type;
        $s['s_t1']   = $space->s_t1;
        $s['s_t2']   = $space->s_t2;
        //$s['s_img']  = $space->s_img;
        $s['s_img']  = '';
        $_file = \humhub\modules\file\models\File::findOne(['guid' => $space->s_img]);
        if( $_file ){
            if ($_file->getMimeBaseType() == "image"){
                $s['s_img']  = $_file->getPreviewImageUrl(200, 200);
            }
        }
        //+more
        $s['description'] = $space->description;
        $s['join_policy'] = $space->join_policy;
        $s['visibility']  = $space->visibility;
        $s['created_at']  = $space->created_at;
        $s['created_by']  = $space->created_by;
        $s['updated_at']  = $space->updated_at;
        $s['updated_by']  = $space->updated_by;
        $s['s_mode']      = $space->s_mode;
        $s['s_achi']      = $space->s_achi;
        $s['s_pg']        = $space->s_pg;
        $s['s_score']     = $space->s_score;

        $_user= User::findOne(['id' => $space->created_by]);
        $user['guid']  = $_user->guid;
        $user['image'] = $_user->getProfileImage()->getUrl();
        $user['displayname'] = $_user->displayName;
        $user['title'] = $_user->profile->title;
        $user['u_v']   = $_user->u_v;

        //if( $space->s_teacher ){
        //    $_user= User::findOne(['id' => $space->s_teacher]);
        //    $t['guid']    = $_user->guid;
        //    $t['image']   = $_user->getProfileImage()->getUrl();
        //    $t['displayname'] = $_user->displayName;
        //    $t['title']   = $_user->profile->title;
        //    $t['u_v']     = $_user->u_v;
        //    $t['country'] = $_user->profile->country;
        //    $t['about']   = $_user->profile->about;
        //}
        //$o['teacher']  = isset($t)?$t:(object)[];
        //$o['teachers'] = \humhub\modules\api\models\CourseEpisode::getTeachers(['space_id' => $space->id]);
        $stream = Yii::createObject([
            'class' => \humhub\modules\api\cccstream\ContentContainerStream4::className(),
            'contentContainer' => $this->contentContainer
        ], ['stream', $this]);
        $posts = $stream->run();
        $teachers = [];
        foreach($posts['output'] AS $post){
            foreach($post['object']['episodes'] AS $p){
                $teachers = array_merge($teachers, $p['teachers']);
            }
        }

        $o['user']  = $user;
        $o['space'] = $s;
        $o['ismember'] = 0;
        $o['teachers'] = $teachers;
        if ($space->isMember()) {
            $o['ismember'] = 1;
        }

        return $o;
    }

    /**
     * 获取指定课程的目录
     *
     * GET /api/course/list
     *
     * get.s : 课程Space的guid
     *
     * @return array 在每一个object中会多返回一个小节列表
     */
    public function actionList(){
        if($this->contentContainer->s_type != 2){
            throw new \yii\web\BadRequestHttpException('课程未找到.');
        }

        $stream = Yii::createObject([
            'class' => \humhub\modules\api\cccstream\ContentContainerStream4::className(),
            'contentContainer' => $this->contentContainer
        ], ['stream', $this]);
        return $stream->run();
    }
}
